package com.ytjj.qmyx.admin.service.impl;

import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.BankerApplyDao;
import com.ytjj.qmyx.admin.dao.BankerProductDao;
import com.ytjj.qmyx.admin.dao.GoodsDao;
import com.ytjj.qmyx.admin.eunm.ActivityTypeNameCode;
import com.ytjj.qmyx.admin.model.request.BankerApplyRequest;
import com.ytjj.qmyx.admin.model.request.SupplyChainProductUpdateStatusRequest;
import com.ytjj.qmyx.admin.model.response.BankerApplyResponse;
import com.ytjj.qmyx.admin.model.response.goods.ProductImgResponse;
import com.ytjj.qmyx.admin.service.BankerApplyService;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.BankerProduct;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.ProductExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 
 * @Version: 1.0
 */
@Service
@Slf4j
public class BankerApplyServiceImpl implements BankerApplyService {

    @Resource
    private BankerApplyDao bankerApplyDao;

    @Resource
    private ChannelProductService channelProductService;

    @Resource
    private GoodsDao goodsDao;

    @Resource
    private BankerProductDao bankerProductDao;

    @Resource
    private SupplyApiConfig supplyApiConfig;

    @Resource
    private ProductMapper productMapper;
    @Override
    public CommonPage<BankerApplyResponse> selectList(BankerApplyRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<BankerApplyResponse> pageList = bankerApplyDao.selectList(request);
        if (!CollectionUtils.isEmpty(pageList)) {
            for (BankerApplyResponse response : pageList) {
                if (response.getBankerProductId() != null) {
                    List<String> typeList = bankerApplyDao.getActivityType(response.getBankerProductId());
                    String activityType = "";
                    if (!CollectionUtils.isEmpty(typeList)) {
                        activityType = typeList.get(0);
                    }
                    response.setActivityType(ActivityTypeNameCode.getName(activityType));
                }
            }
        }
        return CommonPage.restPage(pageList);
    }

    @Override
    public String newSelectList(BankerApplyRequest request) {
        String json = JSON.toJSONString(request);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/applyList", json, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void downStatus(Integer bankerProductId) {
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andBankerProductIdEqualTo(bankerProductId).andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(productExample);
        if (!CollectionUtils.isEmpty(products)){
            products.stream().forEach(item ->{
                channelProductService.putOutChannelProduct(item.getId(),2,"供应商申请下架：商品已下架");
            });
        }

        SupplyChainProductUpdateStatusRequest request = new SupplyChainProductUpdateStatusRequest();
        List<Integer> ids = new ArrayList<>();
        ids.add(bankerProductId);
        request.setIds(ids);
        request.setStatus(2);
        request.setOutOfSelection("供应商申请下架：商品已下架");
        String json = JSON.toJSONString(request);
        HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/productStatusDown", json, supplyApiConfig.getHeadsMap());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rollBack(Integer bankerProductId) {
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andBankerProductIdEqualTo(bankerProductId).andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(productExample);
        if (!CollectionUtils.isEmpty(products)){
            products.stream().forEach(item ->{
                channelProductService.putOutChannelProduct(item.getId(),2,"供应商申请下架：商品已下架");
            });
        }

        Map<String, String> map = new HashMap<>();
        map.put("bankerProductId", String.valueOf(bankerProductId));

        String jsonStr = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/bankerApplyRollBack", map, supplyApiConfig.getHeadsMap());
        JSONObject.parseObject(jsonStr, CommonResult.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void newRollBack(Integer bankerProductId) {
        Map map = new HashMap();
        map.put("bankerProductId",bankerProductId);
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/rollBack", map, supplyApiConfig.getHeadsMap());
        log.info("===="+resultJson+"====");
    }

    @Override
    public void synriBankerProductInfo(Integer bankerProductId) {
        try {
            Product product = bankerApplyDao.selectByBankerProductId(bankerProductId);
            //查询供应商商品信息
            BankerProduct bankerProduct = bankerApplyDao.selectById(bankerProductId);
            //同步内容
            bankerProduct.setProductName(product.getProductName());//商品名称
            bankerProduct.setTopCategoryId(product.getTopCategoryId());//一级分类
            bankerProduct.setCategoryId(product.getCategoryId());//二级分类
            bankerProduct.setBottomCategoryId(product.getBottomCategoryId());//三级分类
            bankerProduct.setDescr(product.getDescr());//商品介绍
            bankerProduct.setCostPrice(product.getCostPrice());//成本价
            bankerProduct.setOriginalPrice(product.getOriginalPrice());//市场价
            bankerProduct.setProductImg(product.getProductImg());//商品主图
            bankerProduct.setSceneImg(product.getSceneImg());//场景图
            bankerProduct.setStatus((byte) 2);//产品状态
            bankerProduct.setAuditStatus(2);//审核状态
            bankerProduct.setShrinkImg(product.getShrinkImg());//缩列图
            bankerProduct.setStockEvaluation(product.getStockEvaluation());//测评库存
            bankerProduct.setPv(product.getPv());//点击量
            bankerProduct.setRate(product.getRate());//费率
            bankerProduct.setRecDescr(product.getRecDescr());//推荐描述
            bankerProduct.setRecommendDoc(product.getRecommendDoc());//推荐文案
            bankerProduct.setPrice(product.getPrice());//售价
            bankerProduct.setSpecialId(product.getSpecialId());//专区

            bankerApplyDao.updateBankerProduct(bankerProduct);

            List<ProductImgResponse> bannerList = goodsDao.findImg(product.getId(), "banner");//商品详情图
            List<ProductImgResponse> infoList = goodsDao.findImg(product.getId(), "info");//轮循图
            saveImg(bankerProduct.getId(),bankerProduct.getBankerId(),bannerList,infoList);
        } catch (Exception e) {
            log.error("打回后同步商品信息异常{}", e);
        }
    }

    public void saveImg(Integer productId,Integer bankerId, List<ProductImgResponse> bannerList, List<ProductImgResponse> infoList) {
        bankerProductDao.deleteOldImg(productId,"banner");
        bankerProductDao.deleteOldImg(productId,"info");
        for (ProductImgResponse productImgRequest : bannerList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品轮播图-图片排序值不能为空！");
            }
            productImgRequest.setType("banner");
            productImgRequest.setProductId(productId);
            productImgRequest.setBankerId(bankerId);
        }
        for (ProductImgResponse productImgRequest : infoList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品主图-图片排序值不能为空！");
            }
            productImgRequest.setType("info");
            productImgRequest.setProductId(productId);
            productImgRequest.setBankerId(bankerId);
        }
        bannerList.addAll(infoList);
        bankerProductDao.saveImg(bannerList);
    }

    @Override
    public void returnBack(Integer bankerProductId, Integer bankerId, String remark) {
        Map<String, String> map = new HashMap<>();
        map.put("bankerProductId", String.valueOf(bankerProductId));
        map.put("bankerId", String.valueOf(bankerId));
        map.put("remark", remark);
        String jsonStr = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/returnBack", map, supplyApiConfig.getHeadsMap());
        JSONObject.parseObject(jsonStr, CommonResult.class);
    }

    @Override
    public void newReturnBack(Integer bankerProductId, Integer bankerId, String remark) {
        Map map = new HashMap();
        map.put("bankerProductId",bankerProductId);
        map.put("bankerId",bankerId);
        map.put("remark",remark);
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/returnBack", map, supplyApiConfig.getHeadsMap());
        log.info("===="+resultJson+"====");
    }
}
